package cn.tedu.csmall.passport.security;

import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private AdminMapper adminMapper;

//extends>>>>扩展  (继承是已有的类快速创建新的类)
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security 框架自动调用UserDetailsServiceImpl中的loadUserByUsename方法,参数{}",s);
        AdminLoginInfoVO admin=adminMapper.getLoginInfoByUsername(s);
        if (admin == null) {
            log.debug("没有与用户名【{}】匹配的用户信息，即将抛出异常", s);
            String message="登录失败,用户名不存在!";
            throw new BadCredentialsException(message);
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        for(String permission:admin.getPermissions()){
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }



        AdminDetails adminDetails = new AdminDetails(
                admin.getId(),
                admin.getUsername(),
                admin.getPassword(),
                admin.getEnable() == 1,
                authorities);

           /* UserDetails userDetails= User.builder()
                    //User就是AdminService 认证通过后的当事人Object principal = authenticateResult.getPrincipal();User
                    .username("root")
                    .password("$2a$10$DoQQSh9eAxDRVKADzQ.Q8Oa4QqcpMUR9UmKyptop3i0mwsdfS.wyC")
                    .disabled(admin.getEnable() == 0)
                    .accountLocked(false)
                    .accountExpired(false)
                    .authorities("展示给出的假的权限标识")
                    .build();
            */
        log.debug("即将想Spring Security框架返回UserDetails对象:{}",adminDetails);
            return  adminDetails;


    }
}
